package com.lanhai.zhonglai.dispatch;
 
  
import java.util.ArrayList;
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.lanhai.zhonglai.beans.AgvBean;
import com.lanhai.zhonglai.beans.StationBean;
import com.lanhai.zhonglai.beans.StationCacheBean;
import com.lanhai.zhonglai.beans.StationDataBean;
import com.lanhai.zhonglai.beans.StationMountBean;
import com.lanhai.zhonglai.enums.StationDataTypeEnum;
import com.lanhai.zhonglai.interfaces.IAgv; 
import com.lanhai.zhonglai.interfaces.IAgvEvent;
import com.lanhai.zhonglai.interfaces.IAgvMount;
import com.lanhai.zhonglai.interfaces.ICmdLog;
import com.lanhai.zhonglai.interfaces.IStation; 
import com.lanhai.zhonglai.interfaces.IStationMount;
import com.lanhai.zhonglai.interfaces.IStationProtocol;
import com.lanhai.zhonglai.report.StationStateMap;
import com.lanhai.zhonglai.interfaces.IDot;
import com.lanhai.zhonglai.interfaces.ISendData; 
import com.lanhai.zhonglai.third.StationFactory;
import com.lanhai.zhonglai.utils.Tools;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool; 

/**
 * 设备的处理
 * 
 * @author zhengwei
 *
 */
@EnableAsync
@Service
public class DispatchStation {
 
	
	@Autowired
	IStation iStation;
	
	@Autowired
	IDot iDot;
	
	@Autowired
	IAgv iAgv;
	
	@Autowired
	IAgvEvent iAgvEvent;
	
	@Autowired
	IAgvMount iAgvMount;
	
	@Autowired
	IStationMount iStationMount;
	 
	 

	@Autowired
	ICmdLog iCmdLog; 
	
	@Autowired
	ISendData sendTools;
	  
	@Autowired
	AgvCmdMap agvCmdMap;
	
	
	@Autowired
	JedisPool jedisPool;
	
	@Autowired
	StationStateMap stationMap;
	
	Gson gson = new Gson();
	
 	 
	@Async("agvExecutor") 
	public void resolve(String ip,  byte[] data) { 
		//可能的设备，主要拿cmdsign 
		 String cmdSign=iStation.getCmdSign(ip);
		if(cmdSign==null) { 
		 	System.out.println ("no cmd "+ip);
			 return;
		}
		
		
		IStationProtocol station =StationFactory.getStation(cmdSign);
		if(station==null) { 
		 System.out.println("station is null");
			 return;
		} 
		List<StationDataBean>  beanList=station.analyseData(ip, data);
		if(beanList==null||beanList.size()==0) {
		   iCmdLog.addStationReceiveLog(ip, 0, "无法解析的指令",Tools.byte2HexStr(data),"未知");
		   System.out.println("无法解析的指令来源："+ip);
		   System.out.println("无法解析的指令："+Tools.byte2HexStr(data));
			System.out.println("empty list");
			return;
		}   
		List<StationCacheBean > tmp=new ArrayList<StationCacheBean >  ();
		for(StationDataBean bean:beanList) {
			// 获取真实的设备
			StationBean stationDao = iStation.getBeanByIP(bean.getIp(),   bean.getLine());
			if (stationDao == null) {  
				System.out.println("ip="+bean.getIp()+"   line="+bean.getLine());
				return;
			} 
			try {
			StationCacheBean sb1=new StationCacheBean();
			sb1.setDoPointId(stationDao.getDotno());
			sb1.setInPointId(stationDao.getDotno()-1);
			sb1.setIp(bean.getIp());
			sb1.setLine(stationDao.getSpecialline());
			sb1.setName(stationDao.getStationname());
			sb1.setId(stationDao.getDotno());
			sb1.setStep(stationDao.getProcess());
			 sb1.setState(bean.getEventType().getEventCode());
			 sb1.setStateTitle(bean.getEventType().getEventName());
			tmp.add(sb1);
			}catch(Exception e) {
				
			}
			
			
			int agvid=iDot.getAgvIdByDotNo(stationDao.getDotno()); 
			AgvBean agv=iAgv.getBean(agvid);
			//System.out.println(bean.getIp() );
			//System.out.println(bean.getCmdStr());
			switch (bean.getEventType()) {
			case AllowLeave: 
				 stationMap.saveState(stationDao.getDotno(), bean.getEventType().getEventName());
				iCmdLog.addStationReceiveLog(ip, bean.getLine(), bean.getEventType().getEventName(),bean.getCmdStr(),stationDao.getStationname());
				StationCmdMap.saveState(stationDao.getDotno() , StationDataTypeEnum.AllowLeave); 
			 
				break;
			case Receive:
				 stationMap.saveState(stationDao.getDotno(), bean.getEventType().getEventName());
				//准备收货，更新状态即可  05
				iCmdLog.addStationReceiveLog(ip, bean.getLine(), bean.getEventType().getEventName(),bean.getCmdStr(),stationDao.getStationname());
				 StationCmdMap.saveState(stationDao.getDotno() , StationDataTypeEnum.Receive); 
				 break;
			case AllowTrans: 
				 //允许传输   
				 stationMap.saveState(stationDao.getDotno(), bean.getEventType().getEventName());
				iCmdLog.addStationReceiveLog(ip, bean.getLine(), bean.getEventType().getEventName(),bean.getCmdStr(),stationDao.getStationname());
				StationCmdMap.saveState(stationDao.getDotno() , StationDataTypeEnum.AllowTrans); 
				
				//ALD的在允许传输中也需要更新数量
				/*
				if(stationDao.getCmdSign().equals("ALD")||stationDao.getCmdSign().equals("BSG")) {
					StationMountBean dm=bean.getBean();  
					bean.setDotno(stationDao.getDotno());
					if(dm!=null) {
						dm.setDotno(stationDao.getDotno());
						iStationMount.saveCache(stationDao.getDotno(), dm);
					} 
					 
				}
					*/
				break; 
			case Info: 
				// 更新装卸情况   
				StationMountBean dm=bean.getBean(); 
				if(dm==null) return;
				if(stationDao.getCmdSign().equals("POPAID") ) { 
					iStation.updatePopaidDirection(stationDao.getDotno(), dm.isDirectionOut()); 
					
					if(dm.isDirectionOut()) {
						stationMap.saveState(stationDao.getDotno(), "物料情况:出料");
					}else {
						stationMap.saveState(stationDao.getDotno(), "物料情况:进料");
					}
				}else {
					 stationMap.saveState(stationDao.getDotno(), bean.getEventType().getEventName());
				}
				 /*
				if(StationCmdMap.isSame(stationDao.getDotno(), bean.getCmdStr())) {
					//不到达临界值，相同的指令仍然过滤 
					if(dm.isAllowIn()==false  && dm.isAllowOut() ==false ) {
					 	return;
					}
				}
				*/
				StationCmdMap.save(stationDao.getDotno(), bean.getCmdStr());  
				iCmdLog.addStationReceiveLog(ip, bean.getLine(), bean.getEventType().getEventName(),bean.getCmdStr(),stationDao.getStationname());
			 
				 
				if(agv==null||agv.isTransing()==false) {
					// 更新装载情况,传输过程中不更新  
					 
					bean.setDotno(stationDao.getDotno()); 
					if(dm!=null) {
						dm.setDotno(stationDao.getDotno());
						iStationMount.saveCache(stationDao.getDotno(), dm);
					}   
				}
				 
				break;
			case Stop:
				 stationMap.saveState(stationDao.getDotno(), bean.getEventType().getEventName());
					
				//要求agv停止传输
				if(StationCmdMap.isSame(stationDao.getDotno(), bean.getCmdStr())) {
					return;
				}
				StationCmdMap.save(stationDao.getDotno(), bean.getCmdStr());
				iCmdLog.addStationReceiveLog(ip, bean.getLine(), bean.getEventType().getEventName(),bean.getCmdStr(),stationDao.getStationname());
			 
				if(agv!=null) {  
					iAgvEvent.stopTrans(agv);
					
					agv.setTransing(false);
					iAgv.saveCache(agv);  
				}
				break;
			case Error:
				 stationMap.saveState(stationDao.getDotno(), bean.getEventType().getEventName());
					
				//机台异常  
				if(StationCmdMap.isSame(stationDao.getDotno(), bean.getCmdStr())) {
					return;
				}
				StationCmdMap.save(stationDao.getDotno(), bean.getCmdStr());
				iCmdLog.addStationReceiveLog(ip, bean.getLine(), bean.getEventType().getEventName(),bean.getCmdStr(),stationDao.getStationname());
				   
				AgvBean agve=iAgv.getBean(agvid);
				if(agve!=null) {
					 iAgvEvent.stopTrans(agve);
				}  
				 
				break;
			default:
				break;
			}
		}
		 
		if(tmp.size()>0) {
			new Thread() { 
				@Override
				public void run() {
					saveToRedis(tmp);
				}
				
			}.start();
		}
		
	}
	
	
	void saveToRedis(List<StationCacheBean> list) { 
		Jedis jd = jedisPool.getResource();
		for (StationCacheBean bean : list) {
			String key = "station_" + bean.getId();
			String json = gson.toJson(bean);
			jd.set(key, json);
		}
		jd.close();
	}
}
